package cn.zhy.org.controller;

import cn.zhy.basic.util.AjaxResult;
import cn.zhy.basic.util.PageList;
import cn.zhy.org.domain.Employee;
import cn.zhy.org.query.EmployeeQuery;
import cn.zhy.org.service.IEmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/employee")
public class EmployeeController {

    @Autowired
    private IEmployeeService employeeService;

    //查询单个
    @GetMapping("/{id}")
    public Employee loadById(@PathVariable("id") Long id){
        return  employeeService.loadById(id);
    }

    //查询所有
    @GetMapping
    public List<Employee> loadAll(){
        return employeeService.loadAll();
    }

    //分页+高级查询
    @PostMapping
    public PageList<Employee> queryPage(@RequestBody EmployeeQuery query){
            return  employeeService.queryPage(query);
    }

    //删除一条记录
    @PostMapping("/{id}")
    public AjaxResult remove(@PathVariable("id") Long id){

        try {
            employeeService.remove(id);
            return new AjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false,"删除失败");
        }
    }


    //修改或添加一条记录
    @PutMapping
    public AjaxResult addOrUpdate(@RequestBody Employee employee){

        try {
           if (employee.getId() !=null){
               employeeService.save(employee);
           }else {
               employeeService.update(employee);
           }
            return new AjaxResult();

        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("错误");
        }
    }


    @PatchMapping
    public AjaxResult patchDelete(@RequestBody List<Long> ids){
        try {
            System.out.println(ids);
            employeeService.patchDelete(ids);
            return new AjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false,"删除批量失败");
        }
    }
}
